package com.ee.chat.cps.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ee.chat.common.bean.Result;
import com.ee.chat.common.dao.*;
import com.ee.chat.common.entity.Channel;
import com.ee.chat.common.entity.ChannelUserLog;
import com.ee.chat.common.entity.User;
import com.ee.chat.common.entity.UserInviteLog;
import com.ee.chat.common.serconfig.MyAliOSSConfig;
import com.ee.chat.common.serconfig.MyNeteaseApp;
import com.ee.chat.common.service.IChannelEarnService;
import com.ee.chat.common.service.IChannelShortUrlService;
import com.ee.chat.common.service.IGeneralService;
import com.ee.chat.common.vo.ChannelVO;
import com.ee.chat.cps.admin.service.IChannelOperationService;
import com.ee.chat.cps.admin.service.IPromoteService;
import com.ndhutu.ee.util.MD5Util;
import com.ndhutu.ee.util.StringUtil;
import com.ndhutu.ee.util.netease.im.IMUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author AppiJ
 * @Date 2020/4/2 15:46
 */
@Service
public class PromoteServiceImpl implements IPromoteService {

    @Resource
    ChannelConfigMapper channelConfigMapper;
    @Resource
    ChannelMapper channelMapper;
    @Resource
    ChannelEarnMapper channelEarnMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    SysConfigMapper sysConfigMapper;
    @Resource
    ChannelUserLogMapper channelUserLogMapper;
    @Resource
    UserInviteLogMapper userInviteLogMapper;
    @Resource
    IGeneralService generalService;
    @Resource
    BaseMapper baseMapper;
    @Resource
    MyAliOSSConfig ossConfig;
    @Resource
    MyNeteaseApp app;
    @Resource
    IChannelEarnService channelEarnService;
    @Resource
    IChannelOperationService operationService;
    @Resource
    IChannelShortUrlService channelShortUrlService;

    /**
     * 获取推广地址列表
     * @Author AppiJ
     * @Date 2020/4/2 15:49
     * @return
     */
    @Override
    public Result list(HttpServletRequest request, Integer page, Integer limit) throws Exception {
        Map<String, Object> data = new HashMap<>();

        HttpSession session = request.getSession(true);
        Channel channel = (Channel) session.getAttribute("channelUser");

        Page<Map<String, Object>> p = new Page<>(page, limit);
        IPage<Map<String, Object>> iPage = channelConfigMapper.queryPromoteUrlList(p, channel.getId());
        List<Map<String, Object>> promoteUrls = iPage.getRecords();
        for(Map<String, Object> map : promoteUrls){
            map.put("username", channel.getUsername());
        }

        data.put("promoteUrls", promoteUrls);
        data.put("total", iPage.getTotal());

        operationService.addOperationLog(request, "查看推广地址列表数据");

        return Result.returnSuccess(data);
    }

    /**
     * 获取推广渠道列表
     * @Author AppiJ
     * @Date 2020/4/10 17:01
     * @param
     * @return
     */
    @Override
    public Result channelList(HttpServletRequest request, String keyword, Integer page, Integer limit) throws Exception {
        Map<String, Object> data = new HashMap<>();

        HttpSession session = request.getSession(true);
        Channel channel = (Channel) session.getAttribute("channelUser");

        Page<Map<String, Object>> p = new Page<>(page, limit);
        IPage<Map<String, Object>> iPage = channelMapper.list(p, channel.getId(), keyword, null);
        List<Map<String, Object>> datas = iPage.getRecords();
        for(Map<String, Object> map : datas){
            Integer registerNum = Integer.parseInt(map.get("registerNum")+"");
            Integer rechagePeopleNum = Integer.parseInt(map.get("rechagePeopleNum")+"");
            double rechageRate;
            if(registerNum == 0){
                rechageRate = 0;
            }else{
                rechageRate = new BigDecimal(rechagePeopleNum+"").divide(new BigDecimal(registerNum+""), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).doubleValue();
            }
            map.put("rechageRate", rechageRate+"%");
        }
        data.put("channels", datas);
        data.put("total", iPage.getTotal());

        operationService.addOperationLog(request, "查看推广渠道列表数据");

        return Result.returnSuccess(data);
    }

    /**
     * 获取渠道信息
     * @Author AppiJ
     * @Date 2020/4/13 11:57
     * @param
     * @return
     */
    @Override
    public Result toEditChannel(HttpServletRequest request, Integer id) throws Exception {
        Map<String, Object> data = new HashMap<>();

        Map<String, Object> channelUser = channelMapper.selectChannelVOById(id);
        if(channelUser == null){
            HttpSession session = request.getSession(true);
            Channel channel = (Channel) session.getAttribute("channelUser");

            channelUser = new HashMap<>();

            channelUser.put("first_invite_recharge_rate", channelEarnMapper.selectValue(channel.getId(), "first_invite_recharge_rate"));
            channelUser.put("first_invite_rate", channelEarnMapper.selectValue(channel.getId(), "first_invite_rate"));
            channelUser.put("second_invite_rate", channelEarnMapper.selectValue(channel.getId(), "second_invite_rate"));
            channelUser.put("first_invite_vip_rate", channelEarnMapper.selectValue(channel.getId(), "first_invite_vip_rate"));
            if(channel.getType() == 3){
                channelUser.put("first_invite_user_rate", channelEarnMapper.selectValue(channel.getId(), "first_invite_user_rate"));
            }

            if(channel.getType() != 2 && channel.getType() != 3){
                return Result.returnFailure("参数错误，请联系管理员");
            }
            channelUser.put("pid", channel.getId());
            channelUser.put("type", channel.getType());
        }
        data.put("channelUser", channelUser);

        return Result.returnSuccess(data);
    }

    /**
     * 添加下级渠道
     * @Author AppiJ
     * @Date 2020/4/14 15:02
     * @param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addChannel(HttpServletRequest request, ChannelVO channelVO) throws Exception {

        HttpSession session = request.getSession(true);
        Channel channel = (Channel) session.getAttribute("channelUser");
        if(!channel.getId().equals(channelVO.getPid())){
            return Result.returnFailure("添加者id错误");
        }
        if(!(channel.getType() == 2 || channel.getType() == 3)){
            return Result.returnFailure("不可添加下级渠道");
        }
        if(!channel.getType().equals(channelVO.getType())){
            return Result.returnFailure("添加渠道类型有误");
        }

        Map<String, Object> vo = channelMapper.selectChannelVOById(channel.getId());
        if(channel.getType() == 2){ //cps渠道
            double first_invite_recharge_rate = Double.parseDouble(vo.get("first_invite_recharge_rate").toString());
            double first_invite_vip_rate = Double.parseDouble(vo.get("first_invite_vip_rate").toString());
            double first_invite_rate = Double.parseDouble(sysConfigMapper.getValue("cps_channel_first_invite_rate"));
            double second_invite_rate = Double.parseDouble(sysConfigMapper.getValue("cps_channel_second_invite_rate"));
            if(channelVO.getFirst_invite_recharge_rate() > first_invite_recharge_rate
                    || channelVO.getFirst_invite_vip_rate() > first_invite_vip_rate
                    || channelVO.getFirst_invite_rate() != first_invite_rate
                    || channelVO.getSecond_invite_rate() != second_invite_rate){
                return Result.returnFailure("渠道的奖励比例不正确");
            }

        }else if(channel.getType() == 3){   //工会渠道
            double first_invite_recharge_rate = Double.parseDouble(vo.get("first_invite_recharge_rate").toString());
            double first_invite_vip_rate = Double.parseDouble(sysConfigMapper.getValue("union_channel_first_invite_vip_rate"));
            double first_invite_rate = Double.parseDouble(sysConfigMapper.getValue("union_channel_first_invite_rate"));
            double second_invite_rate = Double.parseDouble(sysConfigMapper.getValue("union_channel_second_invite_rate"));
            double first_invite_user_rate = Double.parseDouble(sysConfigMapper.getValue("union_channel_first_invite_user_rate"));
            if(channelVO.getFirst_invite_recharge_rate() > first_invite_recharge_rate
                    || channelVO.getFirst_invite_vip_rate() != first_invite_vip_rate
                    || channelVO.getFirst_invite_rate() != first_invite_rate
                    || channelVO.getSecond_invite_rate() != second_invite_rate
                    || channelVO.getFirst_invite_user_rate() != first_invite_user_rate){
                return Result.returnFailure("渠道的奖励比例不正确");
            }

        }else{
            return Result.returnFailure("参数类型错误");
        }

        QueryWrapper<Channel> wrapper = new QueryWrapper<>();
        wrapper.eq("username", channelVO.getUsername());
        if(channelMapper.selectOne(wrapper) != null){
            return Result.returnFailure("用户名已经被注册");
        }

        if(channelVO.getUserId() != null){
            if(userMapper.selectById(channelVO.getUserId()) == null){
                return Result.returnFailure("用户不存在");
            }

            if(channelMapper.selectByUserId(channelVO.getUserId()) != null){
                return Result.returnFailure("用户已经是渠道商");
            }

            ChannelUserLog channelUserLog = channelUserLogMapper.selectByUserId(channelVO.getUserId());
            UserInviteLog userInviteLog = userInviteLogMapper.selectByUserId(channelVO.getUserId());
            boolean flag = false;
            if(channelUserLog != null && channelUserLog.getChannelId().equals(channel.getId())){
                flag = true;
            }
            if(userInviteLog != null && userInviteLog.getInviteUserId().equals(channel.getUserId())){
                flag = true;
            }
            if(!flag){
                return Result.returnFailure("不能添加非渠道直接邀请的用户");
            }
        }else {
            QueryWrapper<User> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("phone", channelVO.getLinkPhone());
            User user = userMapper.selectOne(wrapper1);
            if(user != null){
                return Result.returnFailure("该手机号已被注册使用，请更换手机号");
            }

            //注册app账号
            user = new User();
            user.setId(generalService.getNewUserId());
            user.setInviteCode(generalService.getNewInviteCode());
            user.setToken(StringUtil.getUUIDStr());
            user.setPhone(channelVO.getLinkPhone());
            user.setName(baseMapper.getRandomUserName());
            user.setIcon(baseMapper.getRandomUserIcon());

            //网易IM注册
            String imToken = "123456";
            String ossUrl = "https://"+ossConfig.getBucketName()+"."+ossConfig.getEndpoint()+"/";

            try {
                IMUtil.create(app.getIdPrefix()+user.getId(), user.getName(), ossUrl+user.getIcon(), imToken, app);
            } catch(Exception e){
                IMUtil.update(app.getIdPrefix()+user.getId(), imToken, app);
                IMUtil.updateUinfo(app.getIdPrefix()+user.getId(), user.getName(), ossUrl+user.getIcon(), null, app);
            }
            user.setImToken(imToken);
            userMapper.insert(user);

            channelVO.setUserId(user.getId());
        }

        //渠道注册
        channelVO.setCode(generalService.getNewChannelCode());
        channelVO.setPassword(MD5Util.encode32(channelVO.getPassword()));
        channelMapper.insert(channelVO);

        channelEarnService.updateChannelEarn(channelVO, 0);

        operationService.addOperationLog(request, "添加下级渠道，id："+channelVO.getId());

        //添加渠道对应落地页的短网址
        channelShortUrlService.addChannelShortUrlByPid(channelVO.getId());

        return Result.returnSuccess(null);
    }

    /**
     * 编辑下级渠道
     * @Author AppiJ
     * @Date 2020/4/14 18:30
     * @param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result editChannel(HttpServletRequest request, ChannelVO channelVO) throws Exception {

        Map<String, Object> voMax = channelMapper.selectChannelVOById(channelVO.getPid());
        double maxRechargeRate = Double.parseDouble(voMax.get("first_invite_recharge_rate").toString());
        double maxVipRate = Double.parseDouble(voMax.get("first_invite_vip_rate").toString());

        Map<String, Object> vo = channelMapper.selectChannelVOById(channelVO.getId());
        double first_invite_rate = Double.parseDouble(vo.get("first_invite_rate").toString());
        double second_invite_rate = Double.parseDouble(vo.get("second_invite_rate").toString());

        double minRechargeRate = 0.0;
        double minVipRate = 0.0;
        Map<String, Object> voMin = channelMapper.selectChannelVOByPid(channelVO.getId());
        if(voMin != null){
            minRechargeRate = Double.parseDouble(voMin.get("first_invite_recharge_rate").toString());
            minVipRate = Double.parseDouble(voMin.get("first_invite_vip_rate").toString());
        }

        if(channelVO.getFirst_invite_recharge_rate() > maxRechargeRate || channelVO.getFirst_invite_vip_rate() > maxVipRate
                || channelVO.getFirst_invite_recharge_rate() < minRechargeRate || channelVO.getFirst_invite_vip_rate() < minVipRate
                || channelVO.getFirst_invite_rate() != first_invite_rate || channelVO.getSecond_invite_rate() != second_invite_rate){
            return Result.returnFailure("渠道的奖励比例不正确");
        }

        if(!channelVO.getUsername().equals(vo.get("username"))) {
            QueryWrapper<Channel> wrapper = new QueryWrapper<>();
            wrapper.eq("username", channelVO.getUsername());
            if (channelMapper.selectOne(wrapper) != null) {
                return Result.returnFailure("用户名已经被使用");
            }
        }

        channelMapper.updateById(channelVO);

        channelEarnService.updateChannelEarn(channelVO, 1);

        operationService.addOperationLog(request, "编辑下级渠道，id："+channelVO.getId());

        return Result.returnSuccess(null);
    }

    @Override
    public Result restPwd(HttpServletRequest request, Integer id) throws Exception {
        Channel channel = channelMapper.selectById(id);

        channel.setPassword(MD5Util.encode32("123456"));
        channelMapper.updateById(channel);

        operationService.addOperationLog(request, "重置下级渠道用户密码，id：" + id);

        return Result.returnSuccess(null);
    }
}
